package com.my.system.dao.customer;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.my.system.dao.DataBaseConnection;
import com.my.system.object.client.Transaction;

public class TransactionDao {
	private static Connection con = null;
	private static PreparedStatement psta = null;
	private static ResultSet rs = null;
	static {
		con = DataBaseConnection.getConnection();
	}

	public static List<Transaction> searchTransactionMine(int account_client_id) {
		List<Transaction> list = new ArrayList<Transaction>();
		String sql = "select * from transaction where account_client_id=?";
		try {
			psta = con.prepareStatement(sql);
			psta.setInt(1, account_client_id);
			rs = psta.executeQuery();
			while (rs.next()) {
				int id = rs.getInt(1);
				double value = rs.getDouble(2);
				String create_time = rs.getDate(3).toString();
				int transaction_type = rs.getInt(4);
				int account_user_id = rs.getInt(5);
				Transaction tc = new Transaction(id, value, create_time,
						transaction_type, account_user_id);
				list.add(tc);

			}
			if (list.size() > 0) {
				return list;
			}

		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				if (psta != null) {
					psta.close();
				}
				if (rs != null) {
					psta.close();
				}
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		return null;
	}

	public static boolean insertTransaction(Transaction tc) {
		String sql="insert into transaction("
				+ "value,"
				+ "transaction_type_id,"
				+ "account_client_id)"
				+ "value(?,?,?)";
		try {
			psta=con.prepareStatement(sql);
			psta.setDouble(1, tc.getValue());
			psta.setInt(2, tc.getTransaction_type());
			psta.setInt(3, tc.getAccount_user_id());
			con.setAutoCommit(false);
			int i=psta.executeUpdate();
			con.commit();
			con.setAutoCommit(true);
			if(i>0){
				return true;
			}
		} catch (SQLException e) {
			try {
				con.rollback();
			} catch (SQLException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			try {
				if (psta != null) {
					psta.close();
				}
				if (rs != null) {
					psta.close();
				}
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		
		return false;
		

	}
}
